package com.zdkj.subway.check.controller.subwayRat.conductorDifferences.shoupiaoyuan;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.stationTiecketManager.xianWngCJXXQR.shouRuJS.BomUtil;
import com.zdkj.subway.check.controller.subwayRat.conductorDifferences.passengersTransaction.SwStInputPassengerWorkController;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.*;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.SwAuCenterConductorAmountDifferenceService;
import com.zdkj.subway.check.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

/**
 * 售票员票款差异审核主页
 */
@Slf4j
@RestController
@RequestMapping("/check")
public class SwAuCenterConductorAmountDifferenceController {
    @Resource
    SwAuCenterConductorAmountDifferenceMapper swAuCenterConductorAmountDifferenceMapper;
    @Resource
    SwAuCenterConductorAmountDifferenceService swAuCenterConductorAmountDifferenceService;
    @Resource
    SwAuConductorToBeCheckedMapper swAuConductorToBeCheckedMapper;
    @Resource
    SwAuConductorNoticeMapper swAuConductorNoticeMapper;
    @Resource
    SwStReportErrorAlterAppayMapper swStReportErrorAlterAppayMapper;
    @Resource
    private SwStReportErrorAlterAppayDetailMapper swStReportErrorAlterAppayDetailMapper;
    @Resource
    SwAuCenterConductorAmountDifferenceLogMapper swAuCenterConductorAmountDifferenceLogMapper;

    @Autowired
    private SwStInputPassengerWorkMapper swStInputPassengerWorkMapper;
    @Autowired
    private SwStMarketingTicketMapper swStMarketingTicketMapper;

    @Autowired
    private SwStInputPassengerWorkController swStInputPassengerWorkController;

    @Autowired
    private SwStInputPassengerWorkCashMapper swStInputPassengerWorkCashMapper;
    @Autowired
    private SwStInputPassengerWorkElectronMapper swStInputPassengerWorkElectronMapper;
    @Autowired
    private SwStInputPassengerWorkPayMapper swStInputPassengerWorkPayMapper;
    @Autowired
    private SwStInputPassengerWorkSpecialMapper swStInputPassengerWorkSpecialMapper;
    @Autowired
    private SwStInputPassengerWorkFreeMapper swStInputPassengerWorkFreeMapper;
    @Autowired
    private SwStInputPassengerWorkRefundMapper swStInputPassengerWorkRefundMapper;
    @Autowired
    private SwStInputPassengerWorkTicketMapper swStInputPassengerWorkTicketMapper;
    @Autowired
    private SwStInputPassengerWorkOtherMapper swStInputPassengerWorkOtherMapper;
    /**
     * 列表查询
     * @param page
     * @param swAuCenterConductorAmountDifference
     * @param param
     * @return
     */
    @RequestMapping("/getSwAuCenterConductorAmountDifferenceList")
    @ApiOperation(value = "列表查询", notes = "列表查询")
    public R getSwAuCenterConductorAmountDifferenceList(com.baomidou.mybatisplus.extension.plugins.pagination.Page page, SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference, @RequestParam Map<String,Object> param) throws SQLException, ParseException {
        PigxUser user = SecurityUtils.getUser();
        //区分是否是线网人员
        if(user.getBelongToLine()){
            List lineList = LineOrStation.getmanagementLine();
            param.put("lines",lineList);
        }else{
            List lineList = LineOrStation.getLineOrManagementLine();
            param.put("lines",lineList);
        }
		String startdate = (String)param.get("startdate");
		String enddate = (String)param.get("enddate");
        log.error("日期范围查询开始111",param.get("startdate"));
		log.error("日期范围查询开始12222",param.get("enddate"));
		//List<String> dateCondition = param.get("dates1");//.getDates1();
		/*
		if(StringUtils.isNotEmpty(startdate)){
		   param.put("startdate",dateCondition.get(0));
		}
		 log.error("日期范围查询开始2222",dateCondition.size());
	    if (ObjectUtil.isNotEmpty(dateCondition)) {
			param.put("startdate",dateCondition.get(0));
			param.put("enddate",dateCondition.get(1));
			log.error("日期范围查询开始3333",dateCondition.get(0));
			log.error("日期范围查询开始4444",dateCondition.get(1));

        }*/
        //查询列表
        IPage<SwAuCenterConductorAmountDifference> list=swAuCenterConductorAmountDifferenceMapper.getSwAuCenterConductorAmountDifferenceList(page,param);
        //分页对象记录列表
        List<SwAuCenterConductorAmountDifference> records = list.getRecords();
        Date curr_date = new Date();
        String currdateStr = DateFormat.date_ex_str(curr_date,"yyyy-MM-dd")+" 00:00:00";
        Date currdate = DateFormat.panDuanDate(currdateStr);
        for (SwAuCenterConductorAmountDifference record : records) {
            //线路+站点+BOM编号+收益日期+设备操作号+售票员工号（子表）
            // +报表名称（售票员结算单 or 乘客事务 or营销车票  or 配票  or 其他相关数据录入  or  乘客事务即时退换票 or  乘客事务非即时退换票）+ 除了审批不通过
            //售票员票款差异审核 主子表关联查找（工号查找要排序）
            List<SwStReportErrorAlterApply> applies =
                    swStReportErrorAlterAppayMapper.selectList(Wrappers.<SwStReportErrorAlterApply>lambdaQuery()
                            .eq(SwStReportErrorAlterApply::getLineCode, record.getLineCode())
                            .eq(SwStReportErrorAlterApply::getStationCode, record.getStationCode())
                            .eq(SwStReportErrorAlterApply::getBomCode, record.getBomCode())
                            .eq(SwStReportErrorAlterApply::getReprotTime, DateFormat.dateTOLocalDate(record.getRecordTime()))
                            .eq(SwStReportErrorAlterApply::getDeviceNo, record.getEquipmentNumber())
				            .eq(SwStReportErrorAlterApply::getDelFlag, "0")
                            .in(SwStReportErrorAlterApply::getReportNameId, 1, 2, 3, 8, 9, 10, 11)
                            .ne(SwStReportErrorAlterApply::getIsModify,"1")
                            .ne(SwStReportErrorAlterApply::getCheckStatus,"4"));
            List<SwStReportErrorAlterApply> collect = applies.stream().filter(s -> {
                if (s.getNoticeTime() != null) {
                    //利用Calendar 实现 Date日期 通知时间+期限 < 当前时间 过滤掉
                    Date date = null;
                    try {
                        //取到年月日
                        String dateStr = DateFormat.date_ex_str(s.getNoticeTime(),"yyyy-MM-dd")+" 00:00:00";
                        Date noticedate = DateFormat.panDuanDate(dateStr);
                        date = DateFormat.date_add_or_sub_days(noticedate, s.getModifyLimitTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    boolean b = date.compareTo(currdate) >= 0;
                    return b;

                }
                return true;
            }).collect(Collectors.toList());

            //都不是null 说明未完成
            if(CollectionUtil.isNotEmpty(collect)){
                for (SwStReportErrorAlterApply apply : applies) {
                    List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery("SELECT GROUP_CONCAT(STATION_PERSONR_CODE " +
                            "ORDER BY STATION_PERSONR_CODE asc) as stationPersonrCode from sw_st_report_error_alter_appay_detail WHERE " +
                            "RELATIONID = " + apply.getId() + "");
                    if(ObjectUtil.isNotEmpty(maps.get(0).get("stationPersonrCode"))){
                        if(Objects.equals(record.getConductorJobNo(),maps.get(0).get("stationPersonrCode"))){
                            record.setIsModify("0");//0代表待修改
                            break;
                        }
                    }else {
                        record.setIsModify("1");//1代表已完成
                    }
                }
            }else {
                record.setIsModify("1");//1代表已完成
            }

			String yxcpYrp="";
			String yxcpSrp="";
			String yxcpZlljsrp="";
			String isCombin = record.getIsMergeRecord(); // 是否是合并数据
			//查询售票员配票明细
			String sqlPettyTicket = "select a.ticket_type,a.REPLACE_TICKET_NUM,a.WECHAT_SALE_NUM,ALIPY_SALE_NUM,CASH_SALE_NUM,POS_SALE_NUM from sw_st_ticket_petty_add b,sw_st_ticket_petty_add_details a "+
									" where b.id=a.RELATION_ID and b.SUBMIT_STATUS='1' and a.DEL_FLAG='0' and b.DEL_FLAG='0'"+
									" and a.type='2'"+
									" and a.TICKET_NAME='YXCP' and TICKET_TYPE in ('YRP','SRP','ZLLJSRP') "+
									" and b.line_code='"+record.getLineCode()+"' and b.STATION_CODE='"+record.getStationCode()+"' "+
									" and DATE_FORMAT(b.WORKING_START_TIME,'%Y-%m-%d')='"+DateFormat.dateTOLocalDate(record.getRecordTime())+"' "+
									" and b.NS_JOB_NO='"+record.getConductorJobNo()+"' and b.DEVICE_OPERATE_NUM='"+record.getEquipmentNumber()+"'";
			if("1".equals(isCombin)){
				String conductorNo = record.getConductorJobNo();
				String[] strArray = conductorNo.split(",");
				if(strArray!=null && strArray.length>1){
					StringBuilder strBuilder = new StringBuilder();
					for(int i=0;i<strArray.length;i++){
						if(i!=0){
							strBuilder.append(",");
						}
                        strBuilder.append("'").append(strArray[i]).append("'");
					}
                    conductorNo = strBuilder.toString();
				}else{
					conductorNo = "'"+conductorNo+"'";
				}
				sqlPettyTicket = "select a.ticket_type,SUM(a.REPLACE_TICKET_NUM) as REPLACE_TICKET_NUM, SUM(a.WECHAT_SALE_NUM) as WECHAT_SALE_NUM,SUM(ALIPY_SALE_NUM) as ALIPY_SALE_NUM,SUM(CASH_SALE_NUM) as CASH_SALE_NUM,SUM(POS_SALE_NUM) as POS_SALE_NUM from sw_st_ticket_petty_add b,sw_st_ticket_petty_add_details a "+
                                  " where b.id=a.RELATION_ID and b.SUBMIT_STATUS='1' and a.DEL_FLAG='0' and b.DEL_FLAG='0'"+
										" and a.type='2'"+
										" and a.TICKET_NAME='YXCP' and TICKET_TYPE in ('YRP','SRP','ZLLJSRP') "+
										" and b.line_code='"+record.getLineCode()+"' "+
										" and b.STATION_CODE='"+record.getStationCode()+"' "+
										" and DATE_FORMAT(b.WORKING_START_TIME,'%Y-%m-%d')='"+DateFormat.dateTOLocalDate(record.getRecordTime())+"' "+
										" and b.NS_JOB_NO in ("+conductorNo+" )"+
										" and b.DEVICE_OPERATE_NUM in ("+record.getEquipmentNumber()+")"+
                                        " group by a.ticket_type";
			}
            List<Map<String, Object>> listMapsPetty = JdbcUtil.exeSqlQuery(sqlPettyTicket);
			if(ObjectUtil.isNotEmpty(listMapsPetty)){
				for(int m=0;m<listMapsPetty.size();m++){
					Map<String,Object> ticket = listMapsPetty.get(m);
					if(ticket!=null && ticket.size()>0){
						String ticketType = String.valueOf(ticket.get("ticket_type"));
						String wechat = String.valueOf(ticket.get("WECHAT_SALE_NUM"));
						String alipy = String.valueOf(ticket.get("ALIPY_SALE_NUM"));
						String cash = String.valueOf(ticket.get("CASH_SALE_NUM"));
						String pos = String.valueOf(ticket.get("POS_SALE_NUM"));
						String replaceNum = String.valueOf(ticket.get("REPLACE_TICKET_NUM"));
						String tipInfo = "即时替换-"+replaceNum+"张;"+"现金-"+cash+"张;"+"支付宝-"+alipy+"张;"+"微信-"+wechat+"张;"+"POS-"+pos+"张;";
						if("YRP".equals(ticketType)){
							yxcpYrp = tipInfo;
						}
						if("SRP".equals(ticketType)){
							yxcpSrp= tipInfo;
						}
						if("ZLLJSRP".equals(ticketType)){
							yxcpZlljsrp= tipInfo;
						}

					}

				}
				
			 }//查询配票结束

			 record.setYxcpYrp(yxcpYrp);
			 record.setYxcpSrp(yxcpSrp);
			 record.setYxcpZlljsrp(yxcpZlljsrp);  
			 
			 //查询乘客事务福利票等信息
			 log.info("福利票查询：循环开始01"+ LocalDateTime.now());
			 Map<String,String> mapPassage = getSpeicalFreeTicketInfo(record);
			 String freeInput = mapPassage.get("freeInput");//录入免费出战票
			 String freeInterface = mapPassage.get("freeInterface");//接口免费出战票
			 String specialInput = mapPassage.get("specialInput");//录入特殊车票 --福利票
			 String speicalInterface = mapPassage.get("speicalInterface");//接口特殊车票
			 String payInput = mapPassage.get("payInput");//付费出站票录入张数
			 String payInputMoney = mapPassage.get("payInputMoney");//付费出站票录入金额
			
			 String payInterface = mapPassage.get("payInterface");//付费出站票接口张数
			 String payInterfaceMoney = mapPassage.get("payInterfaceMoney");//付费出站票接口金额

			 record.setPassageFree("系统"+freeInterface+"张,车站录入"+freeInput+"张");
			 record.setPassageSpeical("系统"+speicalInterface+"张,车站录入"+specialInput+"张");
			 record.setPassagePay("系统"+payInterface+"张,车站录入"+payInput+"张;系统"+payInterfaceMoney+"元,车站录入"+payInputMoney+"元");
			 log.info("福利票查询：循环结束10"+ LocalDateTime.now());

        }
        list.setRecords(records);
        return  R.ok(list);
    }
    //查询福利票等信息
	private Map<String,String> getSpeicalFreeTicketInfo(SwAuCenterConductorAmountDifference record )throws SQLException, ParseException {
		
		     // 查找福利票和特殊车票数量
			 String freeInput = "0";//录入免费出战票
			 String freeInterface = "0";//接口免费出战票
			 String specialInput = "0";//录入特殊车票 --福利票
			 String speicalInterface = "0";//接口特殊车票
			 String payInput = "0";//付费出站票录入张数
			 String payInputMoney = "0";//付费出站票录入金额

			 String payInterface = "0";//付费出站票接口张数
			 String payInterfaceMoney = "0";//付费出站票接口金额

			 //存在合并的数据
			  // 查找福利票和特殊车票数量
			 String freeInput2 = "0";//录入免费出战票
				
			 String specialInput2 = "0";//录入特殊车票 --福利票
				
			 String payInput2 = "0";//付费出站票录入张数
			 String payInputMoney2 = "0";//付费出站票录入金额

			 String isCombin = record.getIsMergeRecord(); // 是否是合并数据
			 boolean isInQuery = false;
			 String deviceNos = record.getEquipmentNumber();
			 if("1".equals(isCombin)){
				
				String[] strArray = deviceNos.split(",");
				if(strArray!=null && strArray.length>1){
					StringBuilder strBuilder = new StringBuilder();
					for(int i=0;i<strArray.length;i++){
						if(i!=0){
							strBuilder.append(",");
						}
                        strBuilder.append("'").append(strArray[i]).append("'");
					}
                    deviceNos = strBuilder.toString();
					isInQuery=true;
				}else{
					deviceNos = "'"+deviceNos+"'";
				}
			 }

			 Map<String,String> mapReturn  = new HashMap();
             //log.info("福利票查询--乘客事务主表--开始：循环结束01"+ LocalDateTime.now());
			 String sqlInputPassage = "select id from sw_st_input_passenger_work where del_flag=0 and SUBMIT_STATUS='1'"+
				       " and line_code='"+record.getLineCode()+"'" +
                       " and station_code='"+record.getStationCode()+"'" +
				       " and work_date='"+DateFormat.formatDateByRecordTime(record.getRecordTime(),"yyyy-MM-dd")+"' ";
			 if(!isInQuery){
				sqlInputPassage = sqlInputPassage+ " and DEVICE_OPERATE_NUM='"+record.getEquipmentNumber()+"'" ;
			 }else{
				sqlInputPassage = sqlInputPassage+ " and DEVICE_OPERATE_NUM in("+deviceNos+")" ;				
			 }
				      

             List<Map<String, Object>> mapInputPassage = JdbcUtil.exeSqlQuery(sqlInputPassage);

			 //log.info("福利票查询--乘客事务主表--结束：循环结束01"+ LocalDateTime.now());
             String mainId = "";
			 String mainId2 = "";
			 if(mapInputPassage.size()>0){
					 mainId = String.valueOf(mapInputPassage.get(0).get("id"));	
					 if(mapInputPassage.size()==2){
						mainId2 =  String.valueOf(mapInputPassage.get(1).get("id"));	
					 }
              }
			  //log.info("获取的主id=="+mainId);
			 if(!mainId.equals("") && mainId!=null){

				 //-----------------下面是获取录入的数据-----------------------------------
				
               Map req = new HashMap();
               Long relationId = Long.valueOf(mainId);
               req.put("relationId",relationId);
			   //log.info("获取的主id=="+mainId);
			   //log.info("福利票查询--乘客事务子表--开始：循环111102"+ LocalDateTime.now());
			    //乘客事务录入明细表【付费出站票发售】
				List<Map<String, Object>> swStInputPassengerWorkPay1 = swStInputPassengerWorkPayMapper.getSwStInputPassengerWorkPayByAudit(req);
				//乘客事务录入明细表【特殊车票发售】
				List<Map<String, Object>> swStInputPassengerWorkSpecial1 = swStInputPassengerWorkSpecialMapper.getSwStInputPassengerWorkSpecialByAudit(req);
				//乘客事务录入明细表【免费出站票发售】
				List<Map<String, Object>> swStInputPassengerWorkFree1 = swStInputPassengerWorkFreeMapper.getSwStInputPassengerWorkFreeByAudit(req);

				//log.info("福利票查询--乘客事务子表--结束：循环111102"+ LocalDateTime.now());

				if(swStInputPassengerWorkPay1!=null && swStInputPassengerWorkPay1.size()>0){
					payInput = String.valueOf(swStInputPassengerWorkPay1.get(0).get("sellNumber"));
					payInputMoney = String.valueOf(swStInputPassengerWorkPay1.get(0).get("amount"));				
				}
				if(swStInputPassengerWorkSpecial1!=null && swStInputPassengerWorkSpecial1.size()>0){
					specialInput = String.valueOf(swStInputPassengerWorkSpecial1.get(0).get("sellNumber"));								
				}
				if(swStInputPassengerWorkFree1!=null && swStInputPassengerWorkFree1.size()>0){
					freeInput = String.valueOf(swStInputPassengerWorkFree1.get(0).get("total"));								
				}			

			 }
			  if(isInQuery && !mainId2.equals("") && mainId2!=null){//存在合并

				 //-----------------下面是获取录入的数据-----------------------------------		    
				
               Map req = new HashMap();
               Long relationId = Long.valueOf(mainId2);
               req.put("relationId",relationId);
			   //log.info("获取的主id=="+mainId);
			   //log.info("福利票查询--乘客事务子表--开始：循环111102"+ LocalDateTime.now());
			    //乘客事务录入明细表【付费出站票发售】
				List<Map<String, Object>> swStInputPassengerWorkPay1 = swStInputPassengerWorkPayMapper.getSwStInputPassengerWorkPayByAudit(req);
				//乘客事务录入明细表【特殊车票发售】
				List<Map<String, Object>> swStInputPassengerWorkSpecial1 = swStInputPassengerWorkSpecialMapper.getSwStInputPassengerWorkSpecialByAudit(req);
				//乘客事务录入明细表【免费出站票发售】
				List<Map<String, Object>> swStInputPassengerWorkFree1 = swStInputPassengerWorkFreeMapper.getSwStInputPassengerWorkFreeByAudit(req);

				//log.info("福利票查询--乘客事务子表--结束：循环111102"+ LocalDateTime.now());

				if(swStInputPassengerWorkPay1!=null && swStInputPassengerWorkPay1.size()>0){
					payInput2 = String.valueOf(swStInputPassengerWorkPay1.get(0).get("sellNumber"));
					payInputMoney2 = String.valueOf(swStInputPassengerWorkPay1.get(0).get("amount"));				
				}
				if(swStInputPassengerWorkSpecial1!=null && swStInputPassengerWorkSpecial1.size()>0){
					specialInput2 = String.valueOf(swStInputPassengerWorkSpecial1.get(0).get("sellNumber"));								
				}
				if(swStInputPassengerWorkFree1!=null && swStInputPassengerWorkFree1.size()>0){
					freeInput2 = String.valueOf(swStInputPassengerWorkFree1.get(0).get("total"));								
				}			

			 }
			 //----------下面获取接口信息--------------------

				 //log.info("福利票查询--接口--免出--开始：循环结束02"+ LocalDateTime.now());
			 //免出
			 String sqlFreeInterface ="select ifnull(sum(transactionNumber),0) as num,ifnull(sum(transactionValue)/100,0) as amount from sc_out_ticket  where equipmenttype='2' and tickettype='0' " +          
                       " and bookdate='"+DateFormat.formatDateByRecordTime(record.getRecordTime(),"yyyy-MM-dd")+"' "+
			           " and lineid='"+record.getLineCode()+"'" +
                       " and stationid='"+record.getStationCode()+"'" ;
						//" and station_equipment_number in ("+bomin+")"+
                       //" and posoperid ='"+record.getEquipmentNumber()+"'";
			  if(!isInQuery){
				sqlFreeInterface = sqlFreeInterface +" and posoperid ='"+record.getEquipmentNumber()+"'";
			  }else{
				sqlFreeInterface = sqlFreeInterface +" and posoperid in ("+deviceNos+")";
			  }

              List<Map<String, Object>> mapsFreeInte = JdbcUtil.exeSqlQuery(sqlFreeInterface);

			  //log.info("福利票查询--接口--免出--结束：循环结束02"+ LocalDateTime.now());
              if(mapsFreeInte.size()>0){
					 freeInterface = String.valueOf(mapsFreeInte.get(0).get("num"));					
              }
              //福利票
			 // log.info("福利票查询--接口--福利票--开始：循环结束02"+ LocalDateTime.now());
			  String sqlSpecial ="select ifnull(sum(sale_carnum),0) as num from sc_fare_statistics  where productType ='12' " +          
                        " and bookdate='"+DateFormat.formatDateByRecordTime(record.getRecordTime(),"yyyyMMdd")+"' "+
                        " and lineid='"+record.getLineCode()+"'" +
                        " and station_number='"+record.getStationCode()+"'" ;					
                       // " and posoperid ='"+record.getEquipmentNumber()+"'";
               if(!isInQuery){
				sqlSpecial = sqlSpecial +" and posoperid ='"+record.getEquipmentNumber()+"'";
			  }else{
				sqlSpecial = sqlSpecial +" and posoperid in ("+deviceNos+")";
			  }
 
               List<Map<String, Object>> mapsSpecialInte = JdbcUtil.exeSqlQuery(sqlSpecial);

			   //log.info("福利票查询--接口--福利票--结束：循环结束02"+ LocalDateTime.now());
               if(mapsSpecialInte.size()>0){
					speicalInterface= String.valueOf(mapsSpecialInte.get(0).get("num"));						              
                }
			  //付费
			  //log.info("福利票查询--接口--付费--开始：循环结束02"+ LocalDateTime.now());
			   String sqlMoney ="select ifnull(sum(transactionNumber),0) as num,CAST(IFNULL(ROUND(SUM(transactionValue) / 100), 0) AS SIGNED) as amount from sc_out_ticket  where equipmenttype='2' and tickettype='1' "+           
                        " and bookdate='"+DateFormat.formatDateByRecordTime(record.getRecordTime(),"yyyy-MM-dd")+"' "+
                        " and lineid='"+record.getLineCode()+"'" +
                        " and stationid='"+record.getStationCode()+"'" ;				
                       // " and posoperid ='"+record.getEquipmentNumber()+"'";
			 if(!isInQuery){
				sqlMoney = sqlMoney +" and posoperid ='"+record.getEquipmentNumber()+"'";
			  }else{
				sqlMoney = sqlMoney +" and posoperid in ("+deviceNos+")";
			  }

              List<Map<String, Object>> mapMoneyInte = JdbcUtil.exeSqlQuery(sqlMoney);

			//log.info("福利票查询--接口--付费--结束：循环结束02"+ LocalDateTime.now());
              if(mapMoneyInte.size()>0){
					 payInterface = String.valueOf(mapMoneyInte.get(0).get("num"));
					 payInterfaceMoney = String.valueOf(mapMoneyInte.get(0).get("amount"));					
               }
			
			 mapReturn.put("freeInput",String.valueOf(Integer.parseInt(freeInput)+Integer.parseInt(freeInput2)));
			 mapReturn.put("freeInterface",freeInterface);
			 mapReturn.put("specialInput",String.valueOf(Integer.parseInt(specialInput)+Integer.parseInt(specialInput2)));
			 mapReturn.put("speicalInterface",speicalInterface);
			 mapReturn.put("payInput",String.valueOf(Integer.parseInt(payInput)+Integer.parseInt(payInput2)));
			 mapReturn.put("payInputMoney",addDecimalStrings(payInputMoney,payInputMoney2));
			 mapReturn.put("payInterface",payInterface);
			 mapReturn.put("payInterfaceMoney",payInterfaceMoney);
			
			 return mapReturn;
	}
	private static String addDecimalStrings(String value1, String value2) {
        // 使用BigDecimal进行精确计算
        BigDecimal num1 = new BigDecimal(value1);
        BigDecimal num2 = new BigDecimal(value2);
        BigDecimal sum = num1.add(num2);
        
        // 返回字符串结果（自动去除末尾多余的0）
        return sum.stripTrailingZeros().toPlainString();
    }

    /**
     * 添加操作
     * @param page
     * @param swAuCenterConductorAmountDifference
     * @param param
     * @return
     */
    @RequestMapping("/addSwAuCenterConductorAmountDifference")
    @ApiOperation(value = "添加操作", notes = "添加操作")
    public Result addSwAuCenterConductorAmountDifference(Page page, SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference, Map<String,String> param){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            swAuCenterConductorAmountDifference.setCreatorId(UserInfo.getId());
            swAuCenterConductorAmountDifference.setCreatorName(UserInfo.getUserName());
            //确认状态默认0
            swAuCenterConductorAmountDifference.setCombinStatus("0");
            //属性copy
            swAuCenterConductorAmountDifference=(SwAuCenterConductorAmountDifference)ObejctFieldsValueNotNull.setValueNoNull(SwAuCenterConductorAmountDifference.class,swAuCenterConductorAmountDifference);
            //添加
            int af=swAuCenterConductorAmountDifferenceMapper.addSwAuCenterConductorAmountDifference(swAuCenterConductorAmountDifference);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
            res.setMsg("添加票款差异表失败");
        }
        return res;
    }

    /**
     * 售票员票款差异审核-加入协查
     * @param ids
     * @return
     */
    @RequestMapping("/jiaRuXieCha")
    @ApiOperation(value = "售票员票款差异审核-加入协查", notes = "售票员票款差异审核-加入协查")
    public Result jiaRuXieCha(String ids){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            for(String id:ids.split(",")){
                SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = swAuCenterConductorAmountDifferenceMapper.selectById(Integer.parseInt(id));

                //如果已经加入协查 跳过
                if(null != swAuCenterConductorAmountDifference.getIsAddAssist() && "1".equals(swAuCenterConductorAmountDifference.getIsAddAssist())){
                    continue;
                }
                SwAuConductorToBeChecked swAuConductorToBeChecked=new SwAuConductorToBeChecked();
                swAuConductorToBeChecked.setDifferenceId(swAuCenterConductorAmountDifference.getId());
                swAuConductorToBeChecked.setLineCode(swAuCenterConductorAmountDifference.getLineCode());
                swAuConductorToBeChecked.setStationCode(swAuCenterConductorAmountDifference.getStationCode());
                swAuConductorToBeChecked.setRecordTime(swAuCenterConductorAmountDifference.getRecordTime());
                swAuConductorToBeChecked.setConductorPersonCode(swAuCenterConductorAmountDifference.getConductorJobNo());
                swAuConductorToBeChecked.setConductorPersonName(swAuCenterConductorAmountDifference.getConductorPersonName());
                swAuConductorToBeChecked.setEquipmentNumber(swAuCenterConductorAmountDifference.getEquipmentNumber());
                swAuConductorToBeChecked.setBomCode(swAuCenterConductorAmountDifference.getBomCode());
                swAuConductorToBeChecked.setAssistState("1");//机电协查状态 待下发
                swAuConductorToBeChecked.setKyAssistInvestStatus("1");//客运协查状态 待下发
                swAuConductorToBeChecked.setJdReplySatus("0");//机电回馈状态
                swAuConductorToBeChecked.setKyReplySatus("0");//客运回馈状态
                swAuConductorToBeChecked.setReplaceStatus("0");
                swAuConductorToBeChecked.setReplaceTime(null);
                swAuConductorToBeChecked.setAssistTime(new Date());
                swAuConductorToBeChecked.setPaidAmount(swAuCenterConductorAmountDifference.getPaidAmount());
                swAuConductorToBeChecked.setSysAmount(swAuCenterConductorAmountDifference.getSysAmount());
                swAuConductorToBeChecked.setScInvestAmount(swAuCenterConductorAmountDifference.getScInvestAmount());
                swAuConductorToBeChecked.setScSellAmount(swAuCenterConductorAmountDifference.getScSellAmount());
                swAuConductorToBeChecked.setScFaretkAmount(swAuCenterConductorAmountDifference.getScFaretkAmount());
                swAuConductorToBeChecked.setDiffMoney(swAuCenterConductorAmountDifference.getDifferenceAmount());
                swAuConductorToBeChecked.setCreatorId(swAuCenterConductorAmountDifference.getCreatorId());
                swAuConductorToBeChecked.setCreateTime(new Date());
                swAuConductorToBeChecked.setRecordState("1");
                Integer af=swAuConductorToBeCheckedMapper.insertSwAuConductorToBeChecked(swAuConductorToBeChecked);

                swAuCenterConductorAmountDifference.setAssitAuditSate("1");
                swAuCenterConductorAmountDifference.setIsAddAssist("1");//是否加入协查
                swAuCenterConductorAmountDifferenceMapper.updateById(swAuCenterConductorAmountDifference);//修改协查状态
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
            res.setMsg("添加票款差异表失败");
        }
        return res;
    }

    /**
     * 售票员票款差异审核-加入通知
     * @param ids
     * @return
     */
    @RequestMapping("/jiaRuNotice")
    @ApiOperation(value = "售票员票款差异审核-加入通知", notes = "售票员票款差异审核-加入通知")
    public Result jiaRuNotice(String ids){
        Result res=new Result(ResultDetailMsg.OK);		
		try {
            for(String id:ids.split(",")){
                SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = swAuCenterConductorAmountDifferenceMapper.selectById(Integer.parseInt(id));

                SwAuConductorNotice swAuConductorNotice=new SwAuConductorNotice();
                swAuConductorNotice.setRelationid(swAuCenterConductorAmountDifference.getId());
                swAuConductorNotice.setLineCode(swAuCenterConductorAmountDifference.getLineCode());
                swAuConductorNotice.setStationCode(swAuCenterConductorAmountDifference.getStationCode());
                swAuConductorNotice.setRecordTime(swAuCenterConductorAmountDifference.getRecordTime());
                //TODO 售票员id需要查询数据库
                swAuConductorNotice.setConductorPersonId(null);
                swAuConductorNotice.setConductorPersonCode(swAuCenterConductorAmountDifference.getConductorJobNo());
                swAuConductorNotice.setConductorPersonName(swAuCenterConductorAmountDifference.getConductorPersonName());
                swAuConductorNotice.setEquipmentNumber(swAuCenterConductorAmountDifference.getEquipmentNumber());
                swAuConductorNotice.setBomCode(swAuCenterConductorAmountDifference.getBomCode());
                swAuConductorNotice.setDifferenceAmount(swAuCenterConductorAmountDifference.getDifferenceAmount());
                //TODO 回复期限
                swAuConductorNotice.setReplyPeriod(CheckAccount.getConductorNoticeLimit());//Integer.valueOf(conductorNoticeLimit.toString()));//TODO 回复期限天数之后是不是改为配置的
                swAuConductorNotice.setIsSupPayment(0);
                swAuConductorNotice.setNoticeState("1");
                swAuConductorNotice.setAppealStatus("1");
                swAuConductorNotice.setAppealType("3");//申诉类型：1:期限内申诉 2:超期申诉 3:未申诉（新加入的数据默认为未申诉）
                swAuConductorNotice.setAuditSate("1");
                swAuConductorNotice.setSendStatus("1");
                swAuConductorNotice.setIsSupPayment(1);//是否补款  0；未加入补款 1；未补款 3；已补款
                swAuConductorNotice.setSendTime(null);
                swAuConductorNotice.setSaleoperatorConfirmStatus("0");
                swAuConductorNotice.setCreatorName(UserInfo.getUserName());
                swAuConductorNotice.setCreatorId(UserInfo.getId());
                swAuConductorNotice.setCreateTime(new Date());

                //加入到售票员票款差异通知
                swAuConductorNoticeMapper.insertSwAuConductorNotice(swAuConductorNotice);

                swAuCenterConductorAmountDifference.setNoticeSate("2"); //已通知
                swAuCenterConductorAmountDifferenceMapper.updateById(swAuCenterConductorAmountDifference);//修改通知状态
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("票款差异通知失败");
        }
        return res;
    }


    /**
     * 售票员票款差异审核-审批通过
     * @param ids
     * @return
     */
    @RequestMapping("/audit_state_pass")
    @ApiOperation(value = "售票员票款差异审核-审批通过", notes = "售票员票款差异审核-审批通过")
    public Result audit_state_pass(String ids){
        Result res=new Result(ResultDetailMsg.OK);
		PigxUser user = SecurityUtils.getUser();
        try {
            for(String id:ids.split(",")){
                SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = swAuCenterConductorAmountDifferenceMapper.selectById(Integer.parseInt(id));

                swAuCenterConductorAmountDifference.setAuditState("1"); //已审核				        
                swAuCenterConductorAmountDifference.setAuditTime(new Date());
                swAuCenterConductorAmountDifference.setAuditPersonCode(user.getUserCode());
                swAuCenterConductorAmountDifference.setAuditPersonName(user.getNikeName());
                swAuCenterConductorAmountDifferenceMapper.updateById(swAuCenterConductorAmountDifference);//修改审核状态

                List<SwStInputPassengerWork> objectsInputWork = new ArrayList<>();
                List<SwStMarketingTicket> objectsMarketing = new ArrayList<>();
                //如果是审核模块合并结算的数据 就去找IsMergeRecord = 1的合并前的数据
                if("1".equals(swAuCenterConductorAmountDifference.getIsMergeRecord())){
                    Integer IsMergeRecord = swAuCenterConductorAmountDifference.getId();
                    List<SwAuCenterConductorAmountDifference> swAuCenterConductorAmountDifferences = swAuCenterConductorAmountDifferenceMapper.selectList(Wrappers.<SwAuCenterConductorAmountDifference>lambdaQuery()
                            .eq(SwAuCenterConductorAmountDifference::getCombinOrderId, IsMergeRecord));
                    for (SwAuCenterConductorAmountDifference auCenterConductorAmountDifference : swAuCenterConductorAmountDifferences) {
                        //同步更新乘客事务审核状态
                        List<SwStInputPassengerWork> swStInputList = findInputWork(auCenterConductorAmountDifference);
                        if(CollectionUtil.isNotEmpty(swStInputList)){
                            objectsInputWork.addAll(swStInputList);
                        }
                        //同步更新营销车票审核状态
                        List<SwStMarketingTicket> swStMarketingList = findMarketingTicket(auCenterConductorAmountDifference);
                        if(CollectionUtil.isNotEmpty(swStMarketingList)){
                            objectsMarketing.addAll(swStMarketingList);
                        }
                    }
                }else {
                    //同步更新乘客事务审核状态
                    List<SwStInputPassengerWork> swStInputList = findInputWork(swAuCenterConductorAmountDifference);
                    if(CollectionUtil.isNotEmpty(swStInputList)){
                        objectsInputWork.addAll(swStInputList);
                    }
                    //同步更新营销车票审核状态
                    List<SwStMarketingTicket> swStMarketingList = findMarketingTicket(swAuCenterConductorAmountDifference);
                    if(CollectionUtil.isNotEmpty(swStMarketingList)){
                        objectsMarketing.addAll(swStMarketingList);
                    }
                }
                //调用乘客事务审核审批方法
                if(CollectionUtil.isNotEmpty(objectsInputWork)){
                    Map<String, String> param = new HashMap<>();
                    List<Long> listLongIds = objectsInputWork.stream().map(SwStInputPassengerWork::getId).collect(Collectors.toList());
                    List<Integer> listIds = JSONArray.parseArray(listLongIds.toString(),Integer.class);
                    param.put("ids",String.valueOf(listIds));
                    swStInputPassengerWorkController.auditAll(param);
                }
                //同步更新营销车票审核状态
                objectsMarketing.forEach(x -> {
                    x.setAuditStatus("1");
                    swStMarketingTicketMapper.updateById(x);
                });

            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("票款差异审核失败");
        }
        return res;
    }

    /**
     * 同步更新营销车票审核状态
     * @param swAuCenterConductorAmountDifference
     * @return
     */
    private List<SwStMarketingTicket> findMarketingTicket(SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference) {
        List<SwStMarketingTicket> marketingTicketList = swStMarketingTicketMapper.selectList(Wrappers.<SwStMarketingTicket>lambdaQuery()
                .eq(SwStMarketingTicket::getLineCode, swAuCenterConductorAmountDifference.getLineCode())
                .eq(SwStMarketingTicket::getStationCode, swAuCenterConductorAmountDifference.getStationCode())
                .eq(SwStMarketingTicket::getOpertorTime, swAuCenterConductorAmountDifference.getRecordTime())
                .eq(SwStMarketingTicket::getConductorJobNo, swAuCenterConductorAmountDifference.getConductorJobNo())
                .eq(SwStMarketingTicket::getDeviceOperateNum, swAuCenterConductorAmountDifference.getEquipmentNumber())
                .eq(SwStMarketingTicket::getBomCode, swAuCenterConductorAmountDifference.getBomCode())
                .eq(SwStMarketingTicket::getApprovalStatus, "1")
                .eq(SwStMarketingTicket::getDelFlag, "0")
        );
        return marketingTicketList;
    }

    /**
     * 同步更新乘客事务审核状态
     * @param swAuCenterConductorAmountDifference
     * @return
     */
    private List<SwStInputPassengerWork> findInputWork(SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference) {
        List<SwStInputPassengerWork> swStInputList = swStInputPassengerWorkMapper.selectList(Wrappers.<SwStInputPassengerWork>lambdaQuery()
                .eq(SwStInputPassengerWork::getLineCode, swAuCenterConductorAmountDifference.getLineCode())
                .eq(SwStInputPassengerWork::getStationCode, swAuCenterConductorAmountDifference.getStationCode())
                .eq(SwStInputPassengerWork::getWorkDate, swAuCenterConductorAmountDifference.getRecordTime())
                .eq(SwStInputPassengerWork::getConductorCode, swAuCenterConductorAmountDifference.getConductorJobNo())
                .eq(SwStInputPassengerWork::getDeviceOperateNum, swAuCenterConductorAmountDifference.getEquipmentNumber())
                .eq(SwStInputPassengerWork::getBomCode, swAuCenterConductorAmountDifference.getBomCode())
                .eq(SwStInputPassengerWork::getSubmitStatus, "1")
                .eq(SwStInputPassengerWork::getDelFlag, "0")
        );
        return swStInputList;
    }

    /**
     * 售票员票款差异审核-合并结算
     * @param ids
     * @return
     */
    @RequestMapping("/mergePersonData")
    @ApiOperation(value = "售票员票款差异审核-合并结算", notes = "售票员票款差异审核-合并结算")
    public Result mergePersonData(String ids){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            QueryWrapper<SwAuCenterConductorAmountDifference> queryWrapper=new QueryWrapper<>();
            queryWrapper.in("id",ids.split(","));
            List<SwAuCenterConductorAmountDifference> swAuCenterConductorAmountDifferences = swAuCenterConductorAmountDifferenceMapper.selectList(queryWrapper);
            queryWrapper.select("sum(paid_amount) as paid_amount",
                    "sum(sys_amount) as sys_amount",
                    "sum(passenger_work_amount) as passenger_work_amount",
				    "sum(single_ticket_amount) as single_ticket_amount",
				    "sum(emergency_amount) as emergency_amount",
				    "sum(market_ticket_amount) as market_ticket_amount",			
                    "sum(difference_amount) as difference_amount",
                    "sum(sc_invest_amount) as sc_invest_amount",
                    "sum(sc_sell_amount) as sc_sell_amount",
                    "sum(sc_faretk_amount) as sc_faretk_amount",
                    "sum(lc_invest_amount) as lc_invest_amount",
                    "sum(lc_sell_amount) as lc_sell_amount",
                    "sum(lc_faretk_amount) as lc_faretk_amount",
                    "sum(acc_invest_amount) as acc_invest_amount",
                    "sum(acc_sell_amount) as acc_sell_amount",
                    "sum(acc_faretk_amount) as acc_faretk_amount",
                    "sum(saleoperator_invest_amount) as saleoperator_invest_amount",
                    "sum(saleoperator_sell_amount) as saleoperator_sell_amount",
                    "sum(saleoperator_faretk_amount) as saleoperator_faretk_amount",
                    "sum(saleoperator_paid_amount) as saleoperator_paid_amount");
            List<Map<String, Object>> maps = swAuCenterConductorAmountDifferenceMapper.selectMaps(queryWrapper);//金额合并综合
            Map<String, Object> amount_sum = maps.get(0);

            List<String> conductor_job_nos=new ArrayList<>();
            List<String> conductor_job_names=new ArrayList<>();
            List<String> bom_code_s=new ArrayList<>();
            List<String> equipment_number_s=new ArrayList<>();

            String isHaveBus="0";//是否有乘客事物
			String isHaveMarket="0";//是否有营销车票
            Date incomeSettleBeginTime=null;
            Date incomeSettleEndTime=null;
            Date recordTime=null;
            Date auditTime=null;
            for(SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference:swAuCenterConductorAmountDifferences){
                conductor_job_nos.add(swAuCenterConductorAmountDifference.getConductorJobNo());
                conductor_job_names.add(swAuCenterConductorAmountDifference.getConductorPersonName());
                bom_code_s.add(swAuCenterConductorAmountDifference.getBomCode());
                equipment_number_s.add(swAuCenterConductorAmountDifference.getEquipmentNumber());

                if("1".equals(swAuCenterConductorAmountDifference.getIsHaveBus())){ //有乘客事务的
                    isHaveBus="1";
                }
				if("1".equals(swAuCenterConductorAmountDifference.getIsHaveMarket())){ //有营销车票的
                    isHaveMarket="1";
                }
                //结算日期的
                if(incomeSettleBeginTime==null){
                    incomeSettleBeginTime=swAuCenterConductorAmountDifference.getIncomeSettleBeginTime();
                    incomeSettleEndTime = swAuCenterConductorAmountDifference.getIncomeSettleEndTime();
                }else {
                    if(incomeSettleBeginTime.compareTo(swAuCenterConductorAmountDifference.getIncomeSettleBeginTime())>0){
                        incomeSettleBeginTime=swAuCenterConductorAmountDifference.getIncomeSettleBeginTime();
                    }
                    if(incomeSettleEndTime.compareTo(swAuCenterConductorAmountDifference.getIncomeSettleEndTime())<0){
                        incomeSettleEndTime=swAuCenterConductorAmountDifference.getIncomeSettleEndTime();
                    }
                }

                if(recordTime==null || recordTime.compareTo(swAuCenterConductorAmountDifference.getRecordTime())>0){
                    recordTime=swAuCenterConductorAmountDifference.getRecordTime();
                }
                /* 20241106 合并结算时如果有条是有审核时间的系统会有空指针的错误
                if(auditTime==null || auditTime.compareTo(swAuCenterConductorAmountDifference.getAuditTime())>0){
                    auditTime=swAuCenterConductorAmountDifference.getAuditTime();
                }*/

            }

            conductor_job_nos.remove("");
            conductor_job_names.remove("");
            bom_code_s.remove("");
            equipment_number_s.remove("");

            SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference=new SwAuCenterConductorAmountDifference();
            swAuCenterConductorAmountDifference.setLineCode(swAuCenterConductorAmountDifferences.get(0).getLineCode());
            swAuCenterConductorAmountDifference.setStationCode(swAuCenterConductorAmountDifferences.get(0).getStationCode());
            swAuCenterConductorAmountDifference.setIncomeSettleBeginTime(incomeSettleBeginTime);
            swAuCenterConductorAmountDifference.setIncomeSettleEndTime(incomeSettleEndTime);
            swAuCenterConductorAmountDifference.setIncomeSettleId(swAuCenterConductorAmountDifferences.get(0).getIncomeSettleId());
            swAuCenterConductorAmountDifference.setRecordTime(recordTime);
            swAuCenterConductorAmountDifference.setConductorJobNo(String.join(",",conductor_job_nos));
            swAuCenterConductorAmountDifference.setConductorPersonName(String.join(",",conductor_job_names));
            swAuCenterConductorAmountDifference.setEquipmentNumber(String.join(",",equipment_number_s));
            swAuCenterConductorAmountDifference.setBomCode(String.join(",",bom_code_s));

            swAuCenterConductorAmountDifference.setPaidAmount((BigDecimal) amount_sum.get("paid_amount"));
            swAuCenterConductorAmountDifference.setSysAmount((BigDecimal) amount_sum.get("sys_amount"));
            swAuCenterConductorAmountDifference.setPassengerWorkAmount((BigDecimal) amount_sum.get("passenger_work_amount"));
			swAuCenterConductorAmountDifference.setMarketTicketAmount((BigDecimal) amount_sum.get("market_ticket_amount"));
			swAuCenterConductorAmountDifference.setSingleTicketAmount((BigDecimal) amount_sum.get("single_ticket_amount"));
			swAuCenterConductorAmountDifference.setEmergencyAmount((BigDecimal) amount_sum.get("emergency_amount"));
            swAuCenterConductorAmountDifference.setDifferenceAmount((BigDecimal) amount_sum.get("difference_amount"));
            swAuCenterConductorAmountDifference.setAuditTime(auditTime);
            swAuCenterConductorAmountDifference.setSysDataSource(swAuCenterConductorAmountDifferences.get(0).getSysDataSource());
            swAuCenterConductorAmountDifference.setDataSource("2");
            swAuCenterConductorAmountDifference.setScInvestAmount((BigDecimal) amount_sum.get("sc_invest_amount"));
            swAuCenterConductorAmountDifference.setScSellAmount((BigDecimal) amount_sum.get("sc_sell_amount"));
            swAuCenterConductorAmountDifference.setScFaretkAmount((BigDecimal) amount_sum.get("sc_faretk_amount"));
            swAuCenterConductorAmountDifference.setLcInvestAmount((BigDecimal) amount_sum.get("lc_invest_amount"));
            swAuCenterConductorAmountDifference.setLcSellAmount((BigDecimal) amount_sum.get("lc_sell_amount"));
            swAuCenterConductorAmountDifference.setLcFaretkAmount((BigDecimal) amount_sum.get("lc_faretk_amount"));
            swAuCenterConductorAmountDifference.setAccInvestAmount((BigDecimal) amount_sum.get("acc_invest_amount"));
            swAuCenterConductorAmountDifference.setAccSellAmount((BigDecimal) amount_sum.get("acc_sell_amount"));
            swAuCenterConductorAmountDifference.setAccFaretkAmount((BigDecimal) amount_sum.get("acc_faretk_amount"));
            swAuCenterConductorAmountDifference.setSaleoperatorInvestAmount((BigDecimal) amount_sum.get("saleoperator_invest_amount"));
            swAuCenterConductorAmountDifference.setSaleoperatorSellAmount((BigDecimal) amount_sum.get("saleoperator_sell_amount"));
            swAuCenterConductorAmountDifference.setSaleoperatorFaretkAmount((BigDecimal) amount_sum.get("saleoperator_faretk_amount"));
            swAuCenterConductorAmountDifference.setSaleoperatorPaidAmount((BigDecimal) amount_sum.get("saleoperator_paid_amount"));
            swAuCenterConductorAmountDifference.setIsHaveBus(isHaveBus);
			swAuCenterConductorAmountDifference.setIsHaveBus(isHaveMarket);
            swAuCenterConductorAmountDifference.setAuditState("0");
            swAuCenterConductorAmountDifference.setAssitAuditSate("0");
            swAuCenterConductorAmountDifference.setNoticeSate("0");
            swAuCenterConductorAmountDifference.setSuppState("0");//补款状态默认值
            swAuCenterConductorAmountDifference.setIsAddLayerError("0");
            swAuCenterConductorAmountDifference.setIsMergeRecord("1");
            swAuCenterConductorAmountDifference.setMergeConductorJobNo(String.join(",",conductor_job_nos));
            swAuCenterConductorAmountDifference.setMergeConductorPersonName(String.join(",",conductor_job_names));
            swAuCenterConductorAmountDifference.setMergeEquipmentNumber(String.join(",",equipment_number_s));
            swAuCenterConductorAmountDifference.setMergeBomCode(String.join(",",bom_code_s));
            swAuCenterConductorAmountDifference.setIsAddReprotError("0");
            swAuCenterConductorAmountDifference.setIsAddCombinationNotice("1");
            swAuCenterConductorAmountDifference.setReplaceStatus("0");
            swAuCenterConductorAmountDifference.setCombinStatus("0");
            swAuCenterConductorAmountDifference.setRemark("");
			swAuCenterConductorAmountDifference.setGuardTime(swAuCenterConductorAmountDifference.getGuardTime());
			swAuCenterConductorAmountDifference.setGuardEndTime(swAuCenterConductorAmountDifference.getGuardEndTime());
            swAuCenterConductorAmountDifference.setCreatorId(UserInfo.getId());
            swAuCenterConductorAmountDifference.setCreatorName(UserInfo.getUserName());
            swAuCenterConductorAmountDifference.setCreateTime(new Date());

            int i = swAuCenterConductorAmountDifferenceMapper.addSwAuCenterConductorAmountDifference(swAuCenterConductorAmountDifference);

            for(SwAuCenterConductorAmountDifference s:swAuCenterConductorAmountDifferences){
                s.setCombinStatus("1");
                s.setCombinOrderId(swAuCenterConductorAmountDifference.getId());
                swAuCenterConductorAmountDifferenceMapper.updateById(s);
            }

        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("数据合并失败");
        }
        return res;
    }

    /**
     * 售票员票款差异审核-替换金额
     * @param ids
     * @return
     */
    @RequestMapping("/replaceSystemAmount")
    @ApiOperation(value = "售票员票款差异审核-替换金额", notes = "售票员票款差异审核-替换金额")
    public Result replaceSystemAmount(String ids,String dataSource){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            for(String id:ids.split(",")){
                SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = swAuCenterConductorAmountDifferenceMapper.selectById(Integer.parseInt(id));
                JSONObject js=JSONObject.parseObject(JSONObject.toJSONString(swAuCenterConductorAmountDifference));
                BigDecimal systemAmount=getDataSourceData(js,"SellAmount",dataSource)
                        .add(getDataSourceData(js,"InvestAmount",dataSource))
                        .add(getDataSourceData(js,"FaretkAmount",dataSource));

                BigDecimal a = swAuCenterConductorAmountDifference.getPaidAmount().subtract(swAuCenterConductorAmountDifference.getMarketTicketAmount())
                        .subtract(swAuCenterConductorAmountDifference.getPassengerWorkAmount()).subtract(swAuCenterConductorAmountDifference.getSingleTicketAmount()).subtract(swAuCenterConductorAmountDifference.getEmergencyAmount());

                BigDecimal diff=a.subtract(systemAmount); //实点-系统
                String ds="";
                if("sc".equals(dataSource)){
                    ds="1";
                }else if("lc".equals(dataSource)){
                    ds="2";
                }else if("acc".equals(dataSource)){
                    ds="3";
                }else if("spy".equals(dataSource)){
                    ds="4";
                }
                //核对数据来源
                swAuCenterConductorAmountDifference.setSysDataSource(ds);
                //系统数据金额
                swAuCenterConductorAmountDifference.setSysAmount(systemAmount);
                //差异金额
                swAuCenterConductorAmountDifference.setDifferenceAmount(diff);
                swAuCenterConductorAmountDifference.setReplaceStatus("1"); //已替换
                swAuCenterConductorAmountDifferenceMapper.updateById(swAuCenterConductorAmountDifference);//修改审核状态
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("票款差异审核失败");
        }
        return res;
    }

    /**
     * 根据属性和来源获取不同金额
     * @param row
     * @param field
     * @param dataSource
     * @return
     */
    BigDecimal getDataSourceData(JSONObject row,String field,String dataSource){
//        Integer dataSource=Integer.parseInt(row.getString("dataSource"));
            if("sc".equals(dataSource)){
                return row.getBigDecimal("sc"+field);
            }else if("lc".equals(dataSource)){
                return row.getBigDecimal("lc"+field);
            }else if("acc".equals(dataSource)){
                return row.getBigDecimal("acc"+field);
            }else if("spy".equals(dataSource)){
                return row.getBigDecimal("saleoperator"+field);
            }
            return new BigDecimal(0);
    }

    /**
     * 修改操作
     * @param page
     * @param swAuCenterConductorAmountDifference
     * @param param
     * @return
     */
    @ApiOperation(value = "售票员票款差异审核编辑",notes = "售票员票款差异审核编辑")
    @RequestMapping("/updateSwAuCenterConductorAmountDifference")
    @Transactional(rollbackFor = Exception.class)
    public Result updateSwAuCenterConductorAmountDifference(Page page, SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference, Map<String,String> param){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            //修改之前保存记录表
            PigxUser user = SecurityUtils.getUser();
            SwAuCenterConductorAmountDifference amountDifference = swAuCenterConductorAmountDifferenceMapper.selectById(swAuCenterConductorAmountDifference.getId());
            SwAuCenterConductorAmountDifferenceLog amountDifferenceLog = new SwAuCenterConductorAmountDifferenceLog();
            BeanUtils.copyProperties(amountDifference,amountDifferenceLog);
            amountDifferenceLog.setRelationId(amountDifference.getId());
            amountDifferenceLog.setUpdateId(user.getUserCode());
            amountDifferenceLog.setUpdateName(user.getNikeName());
            amountDifferenceLog.setCreateTime(new Date());
            //保存日志
            int b = swAuCenterConductorAmountDifferenceLogMapper.insert(amountDifferenceLog);
            if(b>0){
                swAuCenterConductorAmountDifference.setSysDataSource("7");//人工修改
                swAuCenterConductorAmountDifferenceMapper.updateById(swAuCenterConductorAmountDifference);
            }

        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("添加票款修改失败");
        }
        return res;
    }


    /**
     * 查询日志记录表
     * @return
     */
    @GetMapping("/SwAuCenterConductorAmountDifferenceLogIdList/{id}")
    @ApiOperation(value = "查询日志记录表",notes = "查询日志记录表")
    public Result SwAuCenterConductorAmountDifferenceLogIdList(@PathVariable (value = "id") Integer relationId ){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            res.setData(swAuCenterConductorAmountDifferenceLogMapper.selectList(Wrappers.<SwAuCenterConductorAmountDifferenceLog>lambdaQuery()
                    .eq(SwAuCenterConductorAmountDifferenceLog::getRelationId,relationId)));
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("查询失败");
        }
        return res;
    }

    /**
     * 加入报表差错
     * @param
     * @param ids
     * @return
     */
    @RequestMapping("/addReportErrorFromSPY")
    @ApiOperation(value = "加入报表差错", notes = "加入报表差错")
    public Result addReportError(String ids,String operatorTable,String modifyField,String value){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            if(StringUtils.isEmpty(ids) || StringUtils.isEmpty(operatorTable)){
                log.error("添加报表失败ids:{},表:{}",ids,operatorTable);
                res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
                res.setMsg("添加报表失败");
            }
            modifyField= StringUtils.isEmpty(modifyField)?"Is_add_reprot_error":modifyField;
            value= StringUtils.isEmpty(value)?"1":value;
            String sql="update "+operatorTable;
            sql+=" set "+modifyField+"='"+value+"' where id in("+ids+")";
            Integer integer = JdbcUtil.exeSqlCrud(sql);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("添加报表失败");
        }
        return res;
    }

    /**
     * 修改操作
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/spy_freshAmount")
    @ApiOperation(value = "修改操作", notes = "修改操作")
    public Result spy_freshAmount(Page page, @RequestParam Map<String,Object> param) throws SQLException, ParseException {
        Result res=new Result(ResultDetailMsg.OK);
        param.put("revenueTime",param.get("recordTime"));
        param.put("startTime", DateFormat.ex_strDate_to_date(String.valueOf(param.get("incomeSettleBeginTime")),"yyyyMMdd"));
        param.put("endTime",DateFormat.ex_strDate_to_date(String.valueOf(param.get("incomeSettleEndTime")),"yyyyMMdd"));
        Map<String, BigDecimal> scLcAcc = BomUtil.getScLcAcc(param);
        String dataSourcetype=String.valueOf(param.get("dataSourcetype"));
        SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference=new SwAuCenterConductorAmountDifference();
        swAuCenterConductorAmountDifference.setId(Integer.parseInt(param.get("id")+""));
        //数据来源区分 sc、lc、acc
        if(dataSourcetype.equals("sc")){
            swAuCenterConductorAmountDifference.setScSellAmount(scLcAcc.get("sc_sell"));
            swAuCenterConductorAmountDifference.setScInvestAmount(scLcAcc.get("sc_de"));
            swAuCenterConductorAmountDifference.setScFaretkAmount(scLcAcc.get("sc_su"));
        }else if(dataSourcetype.equals("lc")){
            swAuCenterConductorAmountDifference.setLcSellAmount(scLcAcc.get("lc_sell"));
            swAuCenterConductorAmountDifference.setLcInvestAmount(scLcAcc.get("lc_de"));
            swAuCenterConductorAmountDifference.setLcFaretkAmount(scLcAcc.get("lc_su"));
        }else if(dataSourcetype.equals("acc")){
            swAuCenterConductorAmountDifference.setAccSellAmount(scLcAcc.get("acc_sell"));
            swAuCenterConductorAmountDifference.setAccInvestAmount(scLcAcc.get("acc_de"));
            swAuCenterConductorAmountDifference.setAccFaretkAmount(scLcAcc.get("acc_su"));
        }


        swAuCenterConductorAmountDifferenceMapper.updateById(swAuCenterConductorAmountDifference);

        SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference1 = swAuCenterConductorAmountDifferenceMapper.selectById(Integer.parseInt(param.get("id") + ""));
        res.setData(swAuCenterConductorAmountDifference1);
        return res;
    }

    /**
     * 通过id列表删除售票员票款差异审核主页，只能删除一条数据
	 * 20240730改为删除重复数据（审核数据不能随便删除，只能作废）
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过id列表删除售票员票款差异审核主页", notes = "通过id列表删除售票员票款差异审核主页")
    @SysLog("通过id列表删除售票员票款差异审核主页" )
    @GetMapping("/removeConductorByIds" )
    @Transactional(rollbackFor = Exception.class)
    public R removeByIds(@RequestParam(value = "ids") List<Integer> ids, @RequestParam(value = "flag") String flag) {
        log.info("售票员删除 flag 参数======================="+flag);

        if(ids!=null && ids.size()>0){
			int id = ids.get(0);			
		
			return R.ok(swAuCenterConductorAmountDifferenceService.delRepeatData(id,flag));
        }
		return R.failed("没有选择对应要操作的数据");
		/*
			//删除售票员待协查数据
              swAuConductorToBeCheckedMapper.delete(Wrappers.<SwAuConductorToBeChecked>lambdaQuery().in(SwAuConductorToBeChecked::getDifferenceId,ids));
             //删除售票员票款差通知数据
              swAuConductorNoticeMapper.delete(Wrappers.<SwAuConductorNotice>lambdaQuery().in(SwAuConductorNotice::getRelationid,ids));
              return R.ok(swAuCenterConductorAmountDifferenceMapper.deleteBatchIds(ids));
		*/

    }
	

    /**
     * 通过id列表撤回审核通过的售票员票款差异审核主页
     * 售票员票款差异审核与乘客事务、营销车票撤销审核进行关联撤回
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过id列表撤回审核通过的售票员票款差异审核主页", notes = "通过id列表撤回审核通过的售票员票款差异审核主页")
    @SysLog("通过id列表撤回审核通过的售票员票款差异审核主页" )
    @PutMapping("/revokeBomIds")
    public R revokeIds(@RequestParam(value = "ids") List<Integer> ids) throws Exception {
        LambdaUpdateWrapper<SwAuCenterConductorAmountDifference> lambdaUpdateWrapper = Wrappers.<SwAuCenterConductorAmountDifference>lambdaUpdate()
                .set(SwAuCenterConductorAmountDifference::getAuditState, "0")//撤回审核状态为0
                //.set(SwAuCenterConductorAmountDifference::getAuditTime, null)
                //.set(SwAuCenterConductorAmountDifference::getAuditPersonCode, null)
                //.set(SwAuCenterConductorAmountDifference::getAuditPersonName, null)
                .in(SwAuCenterConductorAmountDifference::getId,ids);
        swAuCenterConductorAmountDifferenceMapper.update(null,lambdaUpdateWrapper);
        //售票员票款差异审核与乘客事务、营销车票撤销审核进行关联撤回
        for(Integer id : ids){
            SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = swAuCenterConductorAmountDifferenceMapper.selectById(id);

            List<SwStInputPassengerWork> objectsInputWork = new ArrayList<>();
            List<SwStMarketingTicket> objectsMarketing = new ArrayList<>();
            //如果是审核模块合并结算的数据 就去找IsMergeRecord = 1的合并前的数据
            if("1".equals(swAuCenterConductorAmountDifference.getIsMergeRecord())){
                Integer IsMergeRecord = swAuCenterConductorAmountDifference.getId();
                List<SwAuCenterConductorAmountDifference> swAuCenterConductorAmountDifferences = swAuCenterConductorAmountDifferenceMapper.selectList(Wrappers.<SwAuCenterConductorAmountDifference>lambdaQuery()
                        .eq(SwAuCenterConductorAmountDifference::getCombinOrderId, IsMergeRecord));
                for (SwAuCenterConductorAmountDifference auCenterConductorAmountDifference : swAuCenterConductorAmountDifferences) {
                    //同步更新乘客事务审核状态
                    List<SwStInputPassengerWork> swStInputList = findInputWork(auCenterConductorAmountDifference);
                    if(CollectionUtil.isNotEmpty(swStInputList)){
                        objectsInputWork.addAll(swStInputList);
                    }
                    //同步更新营销车票审核状态
                    List<SwStMarketingTicket> swStMarketingList = findMarketingTicket(auCenterConductorAmountDifference);
                    if(CollectionUtil.isNotEmpty(swStMarketingList)){
                        objectsMarketing.addAll(swStMarketingList);
                    }
                }
            }else {
                //同步更新乘客事务审核状态
                List<SwStInputPassengerWork> swStInputList = findInputWork(swAuCenterConductorAmountDifference);
                if(CollectionUtil.isNotEmpty(swStInputList)){
                    objectsInputWork.addAll(swStInputList);
                }
                //同步更新营销车票审核状态
                List<SwStMarketingTicket> swStMarketingList = findMarketingTicket(swAuCenterConductorAmountDifference);
                if(CollectionUtil.isNotEmpty(swStMarketingList)){
                    objectsMarketing.addAll(swStMarketingList);
                }
            }
            //调用乘客事务审核审批方法
            if(CollectionUtil.isNotEmpty(objectsInputWork)){
                List<Long> listLongIds = objectsInputWork.stream().map(SwStInputPassengerWork::getId).collect(Collectors.toList());
                List<Integer> listIds = JSONArray.parseArray(listLongIds.toString(),Integer.class);
                auditRevokeAll(listIds);
            }
            //同步更新营销车票审核状态
            objectsMarketing.forEach(x -> {
                x.setAuditStatus("0");
                swStMarketingTicketMapper.updateById(x);
            });

        }
        return R.ok();
    }

    /**
     * 作废BOM数据
     * @param param
     * @return
     */
    @RequestMapping("/cancellationBomDate")
    @ApiOperation(value = "作废BOM数据", notes = "作废BOM数据")
    public R cancellationTvmDate(@RequestParam Map<String,String> param){
        return swAuCenterConductorAmountDifferenceService.invalidTvmData(param);
    }

    /**
     * 乘客事务子表数据同步撤回
     * @param ids
     */
    public void auditRevokeAll(List<Integer> ids) {
        for (Integer id : ids) {
            SwStInputPassengerWork swStInputPassengerWork = new SwStInputPassengerWork();
            swStInputPassengerWork.setId(Long.valueOf(id));
            swStInputPassengerWork.setAuditStatus("1");
            //乘客事务录入主表审核
            swStInputPassengerWorkMapper.updateById(swStInputPassengerWork);
            SwStInputPassengerWorkCash swStInputPassengerWorkCash = new SwStInputPassengerWorkCash();
            UpdateWrapper updateWrapper1 = new UpdateWrapper();
            updateWrapper1.eq("RELATION_ID",id);
            swStInputPassengerWorkCash.setAuditStatus("1");
            //乘客事务录入明细表【现金事务】
            swStInputPassengerWorkCashMapper.update(swStInputPassengerWorkCash,updateWrapper1);
            SwStInputPassengerWorkElectron swStInputPassengerWorkElectron = new SwStInputPassengerWorkElectron();
            swStInputPassengerWorkElectron.setAuditStatus("1");
            //乘客事务录入明细表【电子事务】
            swStInputPassengerWorkElectronMapper.update(swStInputPassengerWorkElectron,updateWrapper1);
            SwStInputPassengerWorkPay swStInputPassengerWorkPay = new SwStInputPassengerWorkPay();
            swStInputPassengerWorkPay.setAuditStatus("1");
            //乘客事务录入明细表【付费出站票发售】
            swStInputPassengerWorkPayMapper.update(swStInputPassengerWorkPay,updateWrapper1);
            SwStInputPassengerWorkSpecial swStInputPassengerWorkSpecial = new SwStInputPassengerWorkSpecial();
            swStInputPassengerWorkSpecial.setAuditStatus("1");
            //乘客事务录入明细表【特殊车票发售】
            swStInputPassengerWorkSpecialMapper.update(swStInputPassengerWorkSpecial,updateWrapper1);
            SwStInputPassengerWorkFree swStInputPassengerWorkFree = new SwStInputPassengerWorkFree();
            swStInputPassengerWorkFree.setAuditStatus("1");
            //乘客事务录入明细表【免费出站票发售】
            swStInputPassengerWorkFreeMapper.update(swStInputPassengerWorkFree,updateWrapper1);
            SwStInputPassengerWorkRefund swStInputPassengerWorkRefund = new SwStInputPassengerWorkRefund();
            swStInputPassengerWorkRefund.setAuditStatus("1");
            //乘客事务录入明细表【故障退款】
            swStInputPassengerWorkRefundMapper.update(swStInputPassengerWorkRefund,updateWrapper1);
            SwStInputPassengerWork swStInputPassengerWork1 = swStInputPassengerWorkMapper.selectById(id);
            SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
            Date workDate = swStInputPassengerWork1.getWorkDate();
            String workDateStr = dff.format(workDate);
            Map req = new HashMap();
            req.put("auditStatus","1");
            req.put("handlePersonCode",swStInputPassengerWork1.getConductorCode());
            req.put("handleTime",workDateStr);
            req.put("lineCode",swStInputPassengerWork1.getLineCode());
            req.put("stationCode",swStInputPassengerWork1.getStationCode());
            //乘客事务退换票
            swStInputPassengerWorkTicketMapper.updateSwStInputPassengerWorkTicket(req);
            req.put("conductorCode",swStInputPassengerWork1.getConductorCode());
            req.put("inputTime",workDateStr);
            //其他相关数据录入
            swStInputPassengerWorkOtherMapper.updateSwStInputPassengerWorkOther(req);

        }
    }
}


